/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.functionmanagement.ui;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Switch;

import com.android.functionmanagement.BaseActivity;
import com.android.functionmanagement.util.JSONUtil;
import com.android.functionmanagement.util.SharedPreferencesUtils;
import com.uwatch.helowin.R;

/**
 * A list view example where the 
 * data comes from a custom
 * ListAdapter
 */
public class AlertPharmacyActivity extends BaseActivity implements OnCheckedChangeListener
{
    
    private ListView mListPh;
    private Switch mSwitchRing;
//    private Switch mSwitchVibate;
	private SharedPreferences mSh;

	@Override
    public void onCreate(Bundle savedInstanceState)
 {
		super.onCreate(savedInstanceState);
		// Use our own list adapter
		setContentView(R.layout.alert_pharmacy_layout);
		mSwitchRing = (Switch) findViewById(R.id.ph_sw_ring);
//		mSwitchVibate = (Switch) findViewById(R.id.ph_sw_vibrate);
		mSwitchRing.setOnCheckedChangeListener(this);
//		mSwitchVibate.setOnCheckedChangeListener(this);
		mListPh = (ListView) findViewById(R.id.list_ph);
		mSh = PreferenceManager.getDefaultSharedPreferences(this);
		mSwitchRing.setChecked(mSh.getBoolean(
				AlertPharmacySettings.PH_RING_ONOFF,
				getResources().getBoolean(R.bool.def_enable_ph_ring)));

//		mSwitchVibate.setChecked(mSh.getBoolean(
//				AlertPharmacySettings.PH_VIBRATE_ONOFF, getResources()
//						.getBoolean(R.bool.def_enable_ph_vibrate)));
		SparseArray<String[]> sp = getListData();
		if (null != sp) {
			boolean[] expanded = new boolean[sp.get(0).length];
			for (int i = 0; i < expanded.length; i++) {
				expanded[i] = true;
			}
			mListPh.setAdapter(new SpeechListAdapter(this, sp.get(0),
					sp.get(1), expanded));

			mListPh.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					((SpeechListAdapter) mListPh.getAdapter()).toggle(position);
				}
			});
		}
	}
    
	@SuppressWarnings("unchecked")
	private SparseArray<String[]> getListData() {
		String dataStrings = SharedPreferencesUtils
				.getParam(this, "medList", "").toString().replace(":", "：")
				.replace("|", "、").replace("=,", "=\"\",");
		try {
			ArrayList<HashMap<String, Object>> datas = (ArrayList<HashMap<String, Object>>) JSONUtil
					.parseJsonResponse(dataStrings);
			if (datas == null)
				return null;
			String[] titles = new String[datas.size()];
			String[] dialogues = new String[datas.size()];
			int i = 0;
			for (HashMap<String, Object> hashMap : datas) {
				dialogues[i] = "";
				for (String key : hashMap.keySet()) {
					String keyString = key;
					if ("medName".equals(key)) {
						titles[i] = hashMap.get(key).toString();
						continue;
					} else if (key.equals("startDate")) {
						keyString = getString(R.string.med_start_date);
						dialogues[i] += "  " + keyString + ": " + "\n" + "    "
								+ hashMap.get(key).toString().replace("、", "|")
								+ "\n";
					} else if (key.equals("dosage")) {
						keyString = getString(R.string.med_dosage);
					} else if (key.equals("period")) {
						keyString = getString(R.string.med_period);
						dialogues[i] += "  " + keyString + ": " + "\n" + "    "
								+ hashMap.get(key).toString().replace("、", "|")
								+ "\n";
					} else if (key.equals("frequency")) {
						keyString = getString(R.string.med_frequency);
						dialogues[i] += "  " + keyString + ": " + "\n" + "    "
								+ hashMap.get(key).toString().replace("、", "|")
								+ "\n";
					} else if (key.equals("beforeOrAfterMeal")) {
						keyString = getString(R.string.med_before_after);
					} else if (key.equals("hours")) {
						keyString = getString(R.string.med_time);
						dialogues[i] += "  " + keyString + ": " + "\n" + "    "
								+ hashMap.get(key).toString().replace("、", "|")
								+ "\n";
					}

				}
				i++;
			}
			SparseArray<String[]> sp = new SparseArray<String[]>(2);
			sp.put(0, titles);
			sp.put(1, dialogues);
			return sp;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    /**
	 * 
	 */
	/* (non-Javadoc)
	 * @see com.android.functionmanagement.BaseActivity#updateDisplayData()
	 */
	@Override
	protected void updateDisplayData() {
		// TODO Auto-generated method stub
		super.updateDisplayData();
		SparseArray<String[]> sp = getListData();
		if (null == sp)
			return;
		final SpeechListAdapter spa = (SpeechListAdapter) mListPh.getAdapter();
		spa.setTitles(sp.get(0));
		spa.setDialogue(sp.get(1));
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				spa.notifyDataSetChanged();
			}
		});
	}

	/**
     * A sample ListAdapter that presents content
     * from arrays of speeches and text.
     *
     */
    private class SpeechListAdapter extends BaseAdapter {
		public SpeechListAdapter(Context context, String[] titles,
				String[] dialogue, boolean[] expanded)
        {
            mContext = context;
            mTitles = titles;
            mDialogue = dialogue;
            mExpanded = expanded;
        }
        
        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         * 
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return mTitles.length;
        }

        /**
         * Since the data comes from an array, just returning
         * the index is sufficent to get at the data. If we
         * were using a more complex data structure, we
         * would return whatever object represents one 
         * row in the list.
         * 
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a SpeechView to hold each row.
         * @see android.widget.ListAdapter#getView(int, android.view.View, android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            SpeechView sv;
            if (convertView == null) {
                sv = (SpeechView) LayoutInflater.from(mContext).inflate(
						R.layout.alert_ph_list_item, null);
            } else {
                sv = (SpeechView)convertView;
            }
            sv.setTitle(mTitles[position]);
            sv.setDialogue(mDialogue[position]);
            sv.setExpanded(mExpanded[position]);
            return sv;
        }

        public void toggle(int position) {
            mExpanded[position] = !mExpanded[position];
            notifyDataSetChanged();
        }
        
        /**
         * Remember our context so we can use it when constructing views.
         */
        private Context mContext;
        
        /**
         * Our data, part 1.
         */
        private String[] mTitles;
        
        /**
		 * @param mTitles the mTitles to set
		 */
		public void setTitles(String[] mTitles) {
			this.mTitles = mTitles;
		}

		/**
		 * @param mDialogue the mDialogue to set
		 */
		public void setDialogue(String[] mDialogue) {
			this.mDialogue = mDialogue;
		}

		/**
		 * @param mExpanded the mExpanded to set
		 */
		public void setExpanded(boolean[] mExpanded) {
			this.mExpanded = mExpanded;
		}

		/**
         * Our data, part 2.
         */
        private String[] mDialogue  ;
        
        /**
         * Our data, part 3.
         */
        private boolean[] mExpanded;
    }

	/* (non-Javadoc)
	 * @see android.widget.CompoundButton.OnCheckedChangeListener#onCheckedChanged(android.widget.CompoundButton, boolean)
	 */
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		switch (buttonView.getId()) {
		case R.id.ph_sw_ring:
			mSh.edit()
					.putBoolean(AlertPharmacySettings.PH_RING_ONOFF, isChecked)
					.commit();
			break;
//		case R.id.ph_sw_vibrate:
//			mSh.edit()
//					.putBoolean(AlertPharmacySettings.PH_VIBRATE_ONOFF,
//							isChecked).commit();
//			break;
		default:
			break;
		}
	}
}
